import React, { useEffect } from 'react';
import { Select, message } from 'antd';
import useProjectStore from '../store/projectStore';
import type { Project } from '../store/projectStore';
import axios from '../utils/axios';
import { API } from '../api';

const { Option } = Select;

const ProjectSelector: React.FC = () => {
  const { projects, setProjects, currentProject, setCurrentProject } = useProjectStore();

  useEffect(() => {
    fetchProjects();
  }, []);

  const fetchProjects = async () => {
    try {
      const response = await axios.get(API.project.list);
      setProjects(response.data);
      if (!currentProject && response.data.length > 0) {
        setCurrentProject(response.data[0]);
      }
    } catch (error) {
      message.error('获取项目列表失败，请检查网络连接或重新登录');
    }
  };

  const handleProjectChange = (projectId: number) => {
    const selectedProject = projects.find((p: Project) => p.id === projectId);
    if (selectedProject) {
      setCurrentProject(selectedProject);
    }
  };

  return (
    <Select
      style={{ width: 200 }}
      value={currentProject?.id}
      onChange={handleProjectChange}
      placeholder="请选择项目"
    >
      {projects.map((project: Project) => (
        <Option key={project.id} value={project.id}>
          {project.name}
        </Option>
      ))}
    </Select>
  );
};

export default ProjectSelector; 